package com.coocaa.aries.jmeter.util;

import com.coocaa.aries.core.base.constant.CharSetConstants;
import com.coocaa.aries.core.base.exception.AriesException;
import com.coocaa.aries.core.base.exception.ExceptionUtil;
import com.coocaa.aries.core.tool.InstanceUtil;
import com.coocaa.aries.jmeter.model.JmxTemplateModel;
import com.coocaa.aries.jmeter.model.RequestModel;
import com.coocaa.aries.jmeter.model.ThreadGroupModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : bijiahao
 * @date : 2019/4/11.
 * @description:
 */
@Slf4j
public class FtlTemplateUtil {

    public static String getTemplateString(String relativeDir, String templateFileName) throws AriesException {
        //创建一个freemarker.template.Configuration实例，它是存储 FreeMarker 应用级设置的核心部分
        //指定版本号
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
        //获得模板文件路径

        try {
            //设置模板目录
            cfg.setDirectoryForTemplateLoading(new File(getTemplateDir(relativeDir)));
            //设置默认编码格式
            cfg.setDefaultEncoding(CharSetConstants.UTF8);

            //数据
            Map<String, Object> data = new HashMap<>(1);

            data.put("data", getJmxModel());

            //从设置的目录中获得模板
            Template template = cfg.getTemplate(templateFileName);

            StringWriter sw = new StringWriter();
            template.process(data, sw);
            sw.flush();
            sw.close();
            return sw.toString();
        } catch (Exception e) {
            Map errMap = InstanceUtil.newHashMap(2);
            errMap.put("relativeDir", relativeDir);
            errMap.put("templateFileName", templateFileName);
            log.error(ExceptionUtil.getErrorPrintLog("获取ftl模板", errMap, e));
            throw new AriesException("获取ftl配置模板异常");
        }
    }

    private static JmxTemplateModel getJmxModel() {
        JmxTemplateModel data = new JmxTemplateModel();
        ThreadGroupModel threadGroup = new ThreadGroupModel();
        threadGroup.setLoops("1000");
        data.setThreadGroup(threadGroup);
        RequestModel request = new RequestModel();
        request.setDomain("localhost");
        data.setRequest(request);
        return data;
    }

    public static void main(String[] args) {
        String data = getTemplateString("jmx", "MyTestPlan.jmx.ftl");
        System.out.println(data);
    }

    public static String getTemplateDir(String relativeDir) {
        StringBuilder absoluteDir = new StringBuilder();
        absoluteDir.append(PathUtil.getClassPath())
                .append("/")
                .append(relativeDir);
        return absoluteDir.toString();
    }

}
